package com.mc.web.controller.lab;

import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.mc.common.constant.Constants;
import com.mc.common.core.domain.model.LoginUser;
import com.mc.common.utils.DateUtils;
import com.mc.common.utils.ServletUtils;
import com.mc.framework.web.service.TokenService;
import com.mc.gpm.domain.GpmShelve;
import com.mc.lab.service.ILabService;
import com.mc.web.controller.gpm.GpmShelveController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mc.common.annotation.Log;
import com.mc.common.core.controller.BaseController;
import com.mc.common.core.domain.AjaxResult;
import com.mc.common.enums.BusinessType;
import com.mc.lab.domain.LabInfo;
import com.mc.lab.service.ILabInfoService;
import com.mc.common.utils.poi.ExcelUtil;
import com.mc.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 实验室 Controller
 *
 * @author mc
 * @date 2021-03-18
 */
@RestController
@RequestMapping("/lab/info")
public class LabInfoController extends BaseController
{
    @Autowired
    private ILabInfoService labInfoService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ILabService labService;

    private static final Logger log = LoggerFactory.getLogger(LabInfoController.class);

    /**
     * 查询实验室 列表
     */
    @PreAuthorize("@ss.hasPermi('lab:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(LabInfo labInfo)
    {
        startPage();
        List<LabInfo> list = labInfoService.selectLabInfoList(labInfo);
        return getDataTable(list);
    }

    /**
     * 导出实验室 列表
     */
    @PreAuthorize("@ss.hasPermi('lab:info:export')")
    @Log(title = "实验室 ", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LabInfo labInfo)
    {
        List<LabInfo> list = labInfoService.selectLabInfoList(labInfo);
        ExcelUtil<LabInfo> util = new ExcelUtil<LabInfo>(LabInfo.class);
        return util.exportExcel(list, "info");
    }

    /**
     * 获取实验室 详细信息
     */
    @PreAuthorize("@ss.hasPermi('lab:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(labInfoService.selectLabInfoById(id));
    }

    /**
     * 新增实验室
     */
    @PreAuthorize("@ss.hasPermi('lab:info:add')")
    @Log(title = "实验室 ", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LabInfo labInfo)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String uuid  = UUID.randomUUID().toString().replaceAll("-","");
        labInfo.setId(uuid);
        labInfo.setCreateUserId(loginUser.getUsername());
        labInfo.setCreateTime(DateUtils.getNowDate());
        labInfoService.insertLabInfo(labInfo);
        try{
            restTemplate(labInfo,"addFeatures");
        }catch (Exception e){
            log.error("入库失败",e);
        }

        return toAjax(1);
    }

    /**
     * 修改实验室
     */
    @PreAuthorize("@ss.hasPermi('lab:info:edit')")
    @Log(title = "实验室 ", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LabInfo labInfo)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        labInfo.setUpdateUserId(loginUser.getUsername());
        labInfo.setUpdateTime(DateUtils.getNowDate());
        restTemplate(labInfo,"addFeatures");
        try{
            restTemplate(labInfo,"updateFeatures");
        }catch (Exception e){
            log.error("入库失败",e);
        }
        return toAjax(labInfoService.updateLabInfo(labInfo));
    }

    /**
     * 删除实验室
     */
    @PreAuthorize("@ss.hasPermi('lab:info:remove')")
    @Log(title = "实验室 ", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String id)
    {
        try{
            restTemplate(labInfoService.selectLabInfoById(id),"deleteFeatures");
        }catch (Exception e){
            log.error("入库失败",e);
        }
        return toAjax(labInfoService.deleteLabInfoById(id));
    }

    /**
     * 修改实验室
     */
    @PreAuthorize("@ss.hasPermi('lab:info:query')")
    @GetMapping("/get/photo/{labId}")
    public AjaxResult getPhoto(@PathVariable String labId)
    {
        return AjaxResult.success(labService.selectLabPhotoPath(labId));
    }

    public String restTemplate(LabInfo labInfo, String action){
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("f","pjson");
        params.add("frollbackOnFailure", "true");
        String cltTime = null;

        if(action.equals("addFeatures")){
            params.add("features", "[{\"attributes\": {\n" +
                    "    \"NAME\": \""+labInfo.getName()+"\",\n" +
                    "    \"CODE\": \""+labInfo.getId()+"\"\n" +
                    "   },\n" +
                    "   \"geometry\": {\n" +
                    "    \"x\": "+labInfo.getX()+",\n" +
                    "    \"y\": "+labInfo.getY()+"\n" +
                    "   }}]");
        }else if(action.equals("updateFeatures")){
            params.add("features", "[{\"attributes\": {\n" +
                    "    \"OBJECTID\": "+selectObjectId(String.valueOf(labInfo.getId()))+",\n" +
                    "    \"NAME\": \""+labInfo.getName()+"\"\n" +
                    "   },\n" +
                    "   \"geometry\": {\n" +
                    "    \"x\": "+labInfo.getX()+",\n" +
                    "    \"y\": "+labInfo.getY()+"\n" +
                    "   }}]");
        }else{
            params.add("objectIds", selectObjectId(String.valueOf(labInfo.getId())));
        }
        log.info(params.toString());
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, null);
        ResponseEntity<String> response = restTemplate.postForEntity(
                Constants.GIS_SERVER_URL2+action,
                requestEntity,
                String .class);
        String jsonObject = response.getBody();
        log.info(jsonObject);
        if(action.equals("addFeatures")){
            return JSONObject.parseObject(jsonObject).getJSONArray("addResults").getJSONObject(0).getString("objectId");
        }else if(action.equals("updateFeatures")){
            return JSONObject.parseObject(jsonObject).getJSONArray("updateResults").getJSONObject(0).getString("objectId");
        }else{
            return JSONObject.parseObject(jsonObject).getJSONArray("deleteResults").getJSONObject(0).getString("objectId");
        }

    }

    public  String selectObjectId(String code){
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("where","code = \""+code+"\"");
        params.add("geometryType","esriGeometryEnvelope");
        params.add("spatialRel","esriSpatialRelIntersects");
        params.add("units","esriSRUnit_Foot");
        params.add("outFields","OBJECTID");
        params.add("returnGeometry","false");

        params.add("returnDistinctValues","false");
        params.add("returnIdsOnly","false");
        params.add("returnCountOnly","false");
        params.add("returnExtentOnly","false");
        params.add("returnZ","false");
        params.add("returnM","false");
        params.add("multipatchOption","xyFootprint");
        params.add("returnTrueCurves","false");
        params.add("returnExceededLimitFeatures","false");
        params.add("returnCentroid","false");
        params.add("sqlFormat","none");
        params.add("featureEncoding","esriDefault");
        params.add("f","pjson");



        String body = null;
        try {
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, null);

            ResponseEntity<String> forEntity = restTemplate.postForEntity(Constants.GIS_SERVER_URL2+"query", requestEntity, String.class);
            body = forEntity.getBody();
        } catch (Exception e) {
        }
        return JSONObject.parseObject(body).getJSONArray("features").getJSONObject(0).getJSONObject("attributes").getString("OBJECTID");
    }
}